package com.itheima.reggie.controller;

import com.itheima.reggie.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * Created by ZhaoJun on 2021/11/24 16:02
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    @Autowired
    private HttpServletResponse response;

    @PostMapping("/upload")
    public R upload(MultipartFile file){
        log.info("文件上传:{}",file);

        String oldName = file.getOriginalFilename();
        String posName = oldName.substring(oldName.lastIndexOf("."));
        System.out.println(posName);
        //拼接一个新的文件名以.jpg结尾
        String preName = UUID.randomUUID().toString().replace("-","");
        String name = preName + posName;
        System.out.println(name);

        //将上传文件保存到指定位置
        File dir = new File(basePath);

        if(!dir.exists()){
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath+name));
        } catch (IOException e) {
            e.printStackTrace();
        }


        return R.success(name);

    }

    @GetMapping("/download")
    public void download(String name){
        log.info("文件加载:{}",name);
        //1. 定义输入流，通过输入流读取文件内容
        try {
            FileInputStream fis = new FileInputStream(new File(basePath+name));
            //2. 通过response对象，获取到输出流
            ServletOutputStream os = response.getOutputStream();
            //3. 通过response对象设置响应数据格式(image/jpeg)
            response.setContentType("image/jpg");
            //4. 通过输入流读取文件数据，然后通过上述的输出流写回浏览器
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes))!=-1){
                os.write(bytes,0,len);
                os.flush();

            }
            //5. 关闭资源
            os.close();
            fis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }




    }

}
